<?php
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'stackoverflow-user.php');

function stackoverflow_get_queue_tag()
{
    $tag_id = get_option('question_robot_tag', 0);

    if ($tag_id > 0) {
        $tag = get_term($tag_id, 'question_tag');
        global $wpdb;
        $tags = get_categories(array(
            'taxonomy' => 'question_tag',
            'hide_empty' => false,
            'orderby' => 'id',
            'order' => 'desc',
            'number' => 1
        ));
        if (count($tags) > 0) {
            if ($tags[0]->term_id == $tag_id) {
                $tags = get_categories(array(
                    'taxonomy' => 'question_tag',
                    'hide_empty' => false,
                    'orderby' => 'id',
                    'order' => 'asc',
                    'number' => 1
                ));
                if (count($tags) > 0) {
                    add_option('question_robot_tag', $tags[0]->term_id) or update_option('question_robot_tag', $tags[0]->term_id);
                }
            } else {
                $row = $wpdb->get_row($wpdb->prepare("select * from $wpdb->terms where term_id>%d order by term_id asc limit 1", $tag_id));
                if ($row) {
                    add_option('question_robot_tag', $row->term_id) or update_option('question_robot_tag', $row->term_id);
                }
            }
        }
        var_dump($tag);
        if ($tag) {
            return $tag->slug;
        }
    } else {
        $tag_args = array(
            'taxonomy' => 'question_tag',
            'hide_empty' => false,
            'orderby' => 'id',
            'order' => 'asc',
            'number' => 2
        );
        $tags = get_categories($tag_args);
        if (count($tags) > 0) {
            if (count($tags) == 2) {
                add_option('question_robot_tag', $tags[1]->term_id) or update_option('question_robot_tag', $tags[1]->term_id);
            }
            return $tags[0]->slug;
        }
    }
    return 'laravel';
}

function stackoverflow_get_questions()
{
    $tag = stackoverflow_get_queue_tag();
    $url = sprintf("https://stackoverflow.com/feeds/tag?tagnames=%s&sort=newest", $tag);
    $log_id = wp_insert_post(array(
        'post_type' => 'robot_history',
        'post_status' => 'publish',
        'post_title' => 'get questions of ' . $tag . ' from stackoverflow',
        'post_author' => stackoverflow_get_anonymous_user_id(),
        'post_content' => json_encode(array('url' => $url, 'tag' => $tag))
    ));
    add_post_meta($log_id, 'robot_type', 'stackoverflow');

    $content = file_get_contents($url);
    $xml = simplexml_load_string($content);
    stackoverflow_handle_question_list($xml);
}

function stackoverflow_handle_question_list($xml)
{
    $args = array(
        'post_type' => 'question',
        'meta_key' => 'item-id',
        'post_status' => 'any',
        'posts_per_page' => 1
    );

    $model = json_decode(json_encode($xml));

    foreach ($model->entry as $entry) {
        $userId = stackoverflow_get_user_id($entry->author);
        $item_id = str_replace('http://stackoverflow.com/q/', '', $entry->id);
        $args['meta_value'] = $item_id;
        $question_posts = get_posts($args);
        if (!$question_posts) {
            if ($entry->category && count($entry->category) > 0) {
                $tags = array_map(function ($k) {
                    return $k->{"@attributes"}->term;
                }, $entry->category);
            } else {
                $tags = array();
            }
            $tags[] = 'Stackoverflow';
            $link = $entry->link->{"@attributes"}->href;
            $postId = wp_insert_post(array(
                'post_title' => $entry->title,
                'post_content' => $entry->summary,
                'post_excerpt' => $entry->summary,
                'post_status' => 'draft',
                'post_name' => str_replace('http://stackoverflow.com/questions/' .
                    $item_id . '/', '', $link),
                'post_author' => $userId,
                'post_type' => 'question'
            ));
            wp_set_object_terms($postId, $tags, 'question_tag');

            update_post_meta($postId, 'published_at', $entry->published);
            update_post_meta($postId, 'updated_at', $entry->updated);
            update_post_meta($postId, 'source_url', $entry->id);
            update_post_meta($postId, 'source', 'stackoverflow');
            update_post_meta($postId, 'link', $link);
            update_post_meta($postId, 'item-id', $item_id);
        }
    }
}